package com.dong.mjblog.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dong.mjblog.entity.UserEntity;
import com.dong.mjblog.service.impl.UserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//标注service，使userImpl可以注入Bean容器
@Service
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserImpl userImpl;

    /**
     * 请求处理之前做拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("token")){
                    String token = cookie.getValue();
                    QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("token",token);
                    UserEntity user = userImpl.getOne(queryWrapper, false);
//                    System.out.println(user);
                    if (user != null){
                        request.getSession().setAttribute("user",user);
                    }
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
